package com.chatroomserver.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.chatroomserver.constant.UserType;
import com.chatroomserver.entity.User;
import com.chatroomserver.exception.ChatroomException;
import com.chatroomserver.utils.CacheUtil;
import com.chatroomserver.utils.JwtUtil;
import com.chatroomserver.utils.SecurityUtil;
import com.chatroomserver.vo.login.LoginVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginService {

    @Resource
    UserService userService;

    @Value("${chatroom.password}")
    private String chatroomPassword;

    @Value("${chatroom.limit}")
    private int chatroomLimit;

    @Resource
    CacheUtil cacheUtil;

    @Resource
    WebSocketService webSocketService;

    public String verify(String password) {
        if (webSocketService.getOnlineNum() >= chatroomLimit) {
            throw new ChatroomException("聊天室人数已满，请稍后再试~");
        }
        String decryptedPassword = SecurityUtil.decryptPassword(password);
        if (!chatroomPassword.equals(decryptedPassword)) {
            throw new ChatroomException("密码错误~");
        }
        Map tokenInfo = new HashMap<String, String>();
        tokenInfo.put("type", "verify");
        return JwtUtil.createToken(tokenInfo);
    }

    public JSONObject login(LoginVo loginVo) {
        if (webSocketService.getOnlineNum() >= chatroomLimit) {
            throw new ChatroomException("聊天室人数已满，请稍后再试~");
        }

        // 根据用户名或邮箱查找用户
        User user = userService.getUserByNameOrEmail(loginVo.getName(),loginVo.getName());
        if (user == null) {
            throw new ChatroomException("用户不存在，请先注册");
        }

        if (!loginVo.getPassword().equals(user.getPassword())) {
            throw new ChatroomException("密码错误");
        }

        // 更新登录时间
        user.setLoginTime(new Date());
        userService.updateById(user);

        // 构建返回的用户信息
        JSONObject userinfo = new JSONObject();
        userinfo.put("userId", user.getId());
        userinfo.put("userName", user.getName());
        userinfo.put("password",user.getPassword());
        userinfo.put("type", user.getType());
        userinfo.put("email", user.getEmail());
        userinfo.put("avatar", user.getAvatar());

        String token = JwtUtil.createToken(userinfo);
        userinfo.put("token", token);
        cacheUtil.putUserSessionCache(user.getId(), token);

        return userinfo;
    }

}
